package com.wangtongxiao.filter;

import com.wangtongxiao.beans.User;
import com.wangtongxiao.services.UserServices;
import jdk.nashorn.internal.objects.NativeUint8Array;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
//没有spring 使用httpServicesRequest获取
        HttpSession session = req.getSession();
//判断是否登陆
        User login = (User) session.getAttribute("user");

        if (login == null) {
            Cookie[] cookies = req.getCookies();

            if (cookies==null){
                res.sendRedirect("/static/login.action");
                return;
            }

            String loginAct = "";
            String loginPwd = "";
            for (Cookie cookie : cookies
            ) {
                if (cookie.getName().equals("loginAct")) {
                    loginAct = cookie.getValue();
                }
                if (cookie.getName().equals("loginPwd")) {
                    loginPwd = cookie.getValue();
                }
            }
//            使用业务查询用户是否存在
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            UserServices bean = context.getBean("UserServicesFilter", UserServices.class);
            User loginTmp = bean.login(loginAct, loginPwd);
            if (loginTmp == null) {
                res.sendRedirect("/static/login.html");
            } else {
//          自定义登陆成功，把数据放到session中
                session.setAttribute("user",loginTmp);
                chain.doFilter(req, res);
            }

        } else {


            chain.doFilter(req, res);
        }

    }
}
